package multi_thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: walt-zhong
 * @createDate: 2021/3/8
 */
public class printABC1 {
    public class print implements Runnable{
        ReentrantLock reentrantLock;
        private int printCount = 10;
        private String printStr;
        private Condition thisCondition;
        private Condition nextCondition;

        public print(ReentrantLock reentrantLock,Condition thisCondition,Condition nextCondition,String printStr){
            this.reentrantLock = reentrantLock;
            this.thisCondition=thisCondition;
            this.nextCondition = nextCondition;
            this.printStr = printStr;
        }


        @Override
        public void run() {
            try {
                reentrantLock.lock();
                for(int i=0;i<printCount;i++){
                    System.out.print(printStr);
                    nextCondition.signal();
                    //thisCondition.await();
                    if(i<printCount-1){
                        thisCondition.await();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }
    }

    public void test(){
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition conditionA = reentrantLock.newCondition();
        Condition conditionB = reentrantLock.newCondition();
        Condition conditionC = reentrantLock.newCondition();

        new Thread(new print(reentrantLock,conditionA,conditionB,"A")).start();
        new Thread(new print(reentrantLock,conditionB,conditionC,"B")).start();
        new Thread(new print(reentrantLock,conditionC,conditionA,"C")).start();
    }

    public static void main(String[] args){
        new printABC1().test();
    }
}
